package com.peak.spring.boot.core.repository;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import com.google.common.collect.Lists;
import com.peak.spring.boot.tools.Emptys;

public class JpaSorts {

	public static Sort asc(String fieldName) {
		Order order = new Order(Direction.ASC, fieldName);
		return new Sort(order);
	}

	public static Sort desc(String fieldName) {
		Order order = new Order(Direction.DESC, fieldName);
		return new Sort(order);
	}

	public static Sort orderBy(String sortString) {
		if (Emptys.isEmpty(sortString)) {
			return null;
		}
		String[] orderBys = StringUtils.split(sortString, ",");
		List<Order> orders = Lists.newArrayList();
		for (String orderBy : orderBys) {
			orders.add(new Order(Direction.fromString(StringUtils.substringAfterLast(orderBy, "_")), StringUtils.substringBeforeLast(orderBy, "_")));
		}
		return new Sort(orders);
	}
}
